package com.aote.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.aote.constant.RedisConstant;
import com.aote.dao.SetmealDao;
import com.aote.entity.PageResult;
import com.aote.entity.QueryPageBean;
import com.aote.pojo.Setmeal;
import com.aote.service.SetmealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfig freeMarkerConfig;
    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录

    @Autowired
    private SetmealDao setmealDao;
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.insert(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckGroup(setmealId,checkgroupIds);
//        传入数据库后将图片名称传入redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
//        当添加套餐后重新生成套餐页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();

    }
//    生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
//        在生成之前要查询数据
        List<Setmeal> list = setmealDao.findAll();
//        需要生成套餐列表静态页面、套餐详情
        generateMobileSetmealListHtml(list);
        generateMobileSetmealDetailHtml(list);

    }
//    生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map=new HashMap();
//        为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

//    生成套餐详情页面，可能有多个
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
           Map map = new HashMap();
           map.put("setmeal",setmealDao.findById(setmeal.getId()));
           generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }
//    用于生成静态页面
    public void generateHtml(String teplateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfig.getConfiguration();
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(teplateName);
//            输出流
            writer=new FileWriter(new File(outPutPath+"/"+htmlPageName));
//            输出文件
            template.process(map,writer);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
//        分页
        PageHelper.startPage(currentPage,pageSize);
//        数据库查询
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

//    通过id查询
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

//    查询关系表
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
       return setmealDao.findCheckItemIdsByCheckGroupId(id);
    }

//    编辑
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.update(setmeal);
//        重新编辑的图片存放到redis中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        setmealDao.deleteSetmealAndCheckGroup(setmeal.getId());
        this.setSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        generateMobileStaticHtml();
    }

//    查询所有套餐
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

//    套餐预约占比数据
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }


    //    设置套餐和检查组多对对关系，操作关系表
    public void setSetmealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){
        if (checkgroupIds!=null && checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> ids = new HashMap<String, Integer>();
                ids.put("setmealId",setmealId);
                ids.put("checkgroupId",checkgroupId);
                setmealDao.insertSetmealAndCheckgroup(ids);
            }
        }
        }

}
